﻿using System;
using System.IO;
using System.Text;
using System.Runtime.Serialization;

namespace Sencha.Serialization
{
	static class XmlObjectSerializerExtention
	{
		public static object ReadObject(this XmlObjectSerializer @this, string input)
		{
			if (input == null)
				throw new ArgumentNullException("input");

			return ReadObject(@this, new StringReader(input));
		}
		public static object ReadObject(this XmlObjectSerializer @this, TextReader input)
		{
			if (input == null)
				throw new ArgumentNullException("input");
			if (@this == null)
				throw new NullReferenceException();

			if (@this is IJsonSerializer)
				return (@this as IJsonSerializer).ReadObject(input);
			else
			{
				var bytes = Json.DefaultEncoding.GetBytes(input.ReadToEnd());
				MemoryStream _stream = new MemoryStream(bytes);
				var deserializedObject = @this.ReadObject(_stream);
				return deserializedObject;
			}
		}
		public static void WriteObject(this XmlObjectSerializer @this, StringBuilder output, object graph)
		{
			WriteObject(@this, new StringWriter(output), graph);
		}
		public static void WriteObject(this XmlObjectSerializer @this, TextWriter output, object graph)
		{
			if (@this == null)
				throw new NullReferenceException();

			if (@this is IJsonSerializer)
				(@this as IJsonSerializer).WriteObject(output, graph);
			else
			{
				MemoryStream _stream = new MemoryStream(10 * 1024);
				@this.WriteObject(_stream, graph);
				_stream.Position = 0;
				output.Write(new StreamReader(_stream, true).ReadToEnd());
			}
		}
	}
}
